import cn from "classnames";
import InputArea from "./InputArea";
import { chatSSE } from "./api";
import { useChatMessages } from "./store";
import Messages from "./Messages";

type Props = {
  className?: string;
};

const TID = "tid-88";

export default function ChatPanel({ className }: Props) {
  const { addHumanMessage, appendAiMessageToken } = useChatMessages(
    (state) => state,
  );

  const handleMessage = async (message: string) => {
    addHumanMessage(message);
    const events = await chatSSE(TID, message);
    for await (const event of events) {
      const data = JSON.parse(event.data || '{"token":""}');
      appendAiMessageToken(data.id, data.type, data.token);
    }
  };

  return (
    <div
      className={cn(
        "border border-indigo-100 rounded-md grid max-w-3xl mx-auto my-4",
        className,
      )}
      style={{ gridTemplateRows: "1fr 120px", height: "calc(100vh - 80px)" }}
    >
      <Messages className="overflow-y-auto p-4" />
      <div className="flex-none p-4">
        <InputArea className="h-full" onSend={handleMessage} />
      </div>
    </div>
  );
}
